/**
 * 用户相关服务
 */

const util = require('util.js');
const api = require('api.js');


/**
 * 调用微信登录
 */
function loginByWeixin(userInfo) {
  let code = null;
  let userid = null;
  return new Promise(function (resolve, reject) {
    return util.login().then((res) => {
      code = res.code;
      userid = wx.getStorageSync('userid');
      return userInfo;
    }).then((userInfo) => {
      //登录远程服务器
      util.request(api.AuthLoginByWeixin, { code: code, id: userid }, 'POST', 'application/json').then(res => {
        if (res.code === 0) {
          //存储用户信息
          wx.setStorageSync('token', res.token);
          // wx.setStorageSync('userid', res.userid);
          resolve(res);
        } else {
          util.showErrorToast(res.errmsg)
          reject(res);
        }
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}

/**
 * 判断用户是否登录
 */
function checkLogin() {
  return new Promise(function (resolve, reject) {
    if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')) {

      util.checkSession().then(() => {
        resolve(true);
      }).catch(() => {
        reject(false);
      });

    } else {
      reject(false);
    }
  });
}

function decryRunData(resRun, sessionKey) {
  return new Promise(function (resolve, reject) {
    util.request(api.DecryRunData,
      {
        encryptedData: resRun.encryptedData,
        iv: resRun.iv,
        sessionKey: sessionKey,
        token: '用户token,如果你只是小程序开发，传openid即：res.data.openid',
        days: 3 //传要协调的天数
      },
      'POST',
      'application/json').then(res => {
        if (res.code === 0) {
          //存储用户信息
          console.log(res)
          resolve(res);
        } else {
          util.showErrorToast(res.errmsg)
          reject(res);
        }
      }).catch((err) => {
        reject(err);
      });
  })
}



module.exports = {
  loginByWeixin,
  checkLogin,
  decryRunData,
};











